<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <!--      <el-form-item label="名称" prop="name">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.name"-->
      <!--          placeholder="请输入名称"-->
      <!--          clearable-->
      <!--          size="small"-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="化验单编号" prop="sheetNo" label-width="140px" >-->
      <!--        <el-input-->
      <!--          v-model="queryParams.sheetNo"-->
      <!--          placeholder="请输入化验单编号"-->
      <!--          clearable-->
      <!--          size="small"-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item label="起始时间">
        <el-date-picker
          v-model="queryParams.dateQuery"
          type="daterange"
          align="right"
          value-format="yyyy-MM-dd"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions">
        </el-date-picker>
      </el-form-item>


      <el-form-item label="汇报人员" prop="reportPerson">

        <el-select clearable v-model="queryParams.reportPerson" filterable placeholder="选择汇报人员" @change="handleChange">
          <el-option
            v-for="user in filteredUsers"
            :key="user.userId"
            :label="user.nickName "
            :value="user.userId">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="部门" prop="deptId">
        <treeselect
          v-model="queryParams.deptId"
          :options="deptOptions"
          :show-count="true"
          placeholder="请选择归属部门"
          style="width: 200px;"
        />
      </el-form-item>
      <!--      <el-form-item label="当日使用车辆" prop="carId" label-width="150px">-->
      <!--        <el-select clearable  v-model="queryParams.carId" filterable placeholder="选择当日使用车辆" @change="handleChange">-->
      <!--          <el-option-->
      <!--            v-for="car in filteredCars"-->
      <!--            :key="car.id"-->
      <!--            :label="car.name + ' (' + car.licensePlate + ')'"-->
      <!--            :value="car.id">-->
      <!--          </el-option>-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->

      <!--      <el-form-item  label="工作人员" prop="workUsers">-->


      <!--        <el-select clearable  v-model="queryParams.workUsers" filterable placeholder="选择工作人员" @change="handleChange">-->
      <!--          <el-option-->
      <!--            v-for="user in filteredUsers"-->
      <!--            :key="user.userId"-->
      <!--            :label="user.nickName + ' (' + user.userName + ')'"-->
      <!--            :value="user.userId">-->
      <!--          </el-option>-->
      <!--        </el-select>-->

      <!--      </el-form-item>-->

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['station:station:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['station:station:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['station:station:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['station:station:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="stationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <!--      <el-table-column label="id" align="center" prop="id" />-->
      <el-table-column label="序号" type="index" width="50" align="center">
        <template slot-scope="scope">
          <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="部门名称" align="center" prop="deptName"  />
      <el-table-column label="数据日期" align="center" prop="name"/>

      <el-table-column label="加油量(吨)" align="center" prop="fuelQuantity"/>
      <el-table-column label="加油(架次)" align="center" prop="oilCount"/>
      <!--      <el-table-column label="化验单编号" align="center" prop="sheetNo" />-->
      <!--      <el-table-column label="存油量" align="center" prop="oilStorage"  />-->
      <el-table-column label="前日迎检情况" align="center" prop="info"/>
      <el-table-column label="异常情况" align="center" prop="error"/>
      <el-table-column label="上报用户" align="center" prop="reportPerson" :formatter="reportPersonFormat"/>
      <el-table-column
        label="当日使用车辆"
        align="center"
        prop="carId"
        :formatter="carFormat"
        show-overflow-tooltip
      >
        <template slot-scope="{ row, column, $index }">
          <span v-html="carFormat(row, column, row.carId)"></span>
        </template>
      </el-table-column>

      <el-table-column
        label="工作人员"
        align="center"
        prop="workPerson"
        :formatter="workPersonFormat"
        show-overflow-tooltip
      >
        <template slot-scope="{ row, column, $index }">
          <span v-html="workPersonFormat(row, column, row.workUserId)"></span>
        </template>
      </el-table-column>

            <el-table-column label="污油罐高度" align="center" prop="dirtyOilTankHeight"  />
<!--      <el-table-column label="污油罐高度" align="center" prop="dirtyOilTankWeight"/>-->

      <!--      <el-table-column label="创建时间" align="center" prop="createDate" width="180">-->
      <!--        <template slot-scope="scope">-->
      <!--          <span>{{ parseTime(scope.row.createDate, '{y}-{m}-{d}') }}</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      <el-table-column label="上报时间" align="center" prop="reportDate" width="180">-->
      <!--        <template slot-scope="scope">-->
      <!--          <span>{{ parseTime(scope.row.reportDate, '{y}-{m}-{d}') }}</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['station:station:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['station:station:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改航空加油站数据上报对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item label="数据日期" prop="name" v-dialog-drag-width="200">
              <el-date-picker
                v-model="form.name"
                type="date"
                placeholder="请输入数据日期"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
              />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="近7天平均加油量" prop="days">
              <el-input disabled v-model="form.avgOil" placeholder="请输入近7天平均加油量" style="width: 200px">
                <template slot="append">(吨)</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!--        <el-form-item label="近7天平均加油量"  prop="avgOil" label-width="150px">-->
        <!--          <el-input-number disabled v-model="form.avgOil" placeholder="近7天平均加油量" />-->
        <!--        </el-form-item>-->

        <!--        <el-form-item label="名称" prop="name">-->
        <!--          <el-input v-model="form.name" placeholder="请输入名称" />-->
        <!--        </el-form-item>-->
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item label="加油(架次)" prop="oilCount">
              <el-input-number :min="0" v-model="form.oilCount" placeholder="请输入加油架次">
              </el-input-number>
            </el-form-item>

          </el-col>
          <el-col :span="10">
            <el-form-item label="加油量(吨)" prop="fuelQuantity">
              <el-input-number :min="0" v-model="form.fuelQuantity" placeholder="请输入加油量" :precision='3'>
              </el-input-number>
            </el-form-item>

          </el-col>

        </el-row>


        <el-divider content-position="center">当日使用温度/密度</el-divider>
        <div v-for="(item, index) in form.rate" :key="index">
          <el-row :gutter="24">
            <el-col :span="7">
              <el-form-item :label="getDensityLabel(index) + ' 视温(摄氏度)'" :prop="'temperature' + index">
                <el-input-number v-model="item.temperature" placeholder="请输入视温(摄氏度)" :precision="2"></el-input-number>
              </el-form-item>
            </el-col>

            <el-col :span="7">
              <el-form-item :label="'视密(克/立方厘米)'" :prop="'density' + index">
                <el-input-number v-model="item.density" placeholder="请输入视密(克/立方厘米)" :precision="4"></el-input-number>
              </el-form-item>
            </el-col>

            <el-col :span="7">
              <el-form-item :label="'化验单编号'" :prop="'sno' + index">
                <el-input v-model="item.sno" placeholder="请输入化验单编号"></el-input>
              </el-form-item>
            </el-col>


            <!-- 行操作按钮 -->
            <el-col :span="3" class="row-actions">
              <el-button
                type="danger"
                icon="el-icon-minus"
                @click="removeDensityRow(index)"
                :disabled="form.rate && form.rate.length <= 1"
                circle
                style="margin-left: 10px;">
              </el-button>
              <el-button
                type="primary"
                icon="el-icon-plus"
                @click="addDensityRow"
                :disabled="form.rate && form.rate.length >= 3"
                circle>
              </el-button>

            </el-col>
          </el-row>
        </div>


        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item label="工作人员" prop="workUsers">
              <el-select clearable multiple v-model="form.workUsers" filterable placeholder="选择工作人员">
                <el-option
                  v-for="user in filteredUsers"
                  :key="user.userId"
                  :label="user.nickName "
                  :value="user.userId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="使用车辆" prop="cars">
              <el-select v-model="form.cars" multiple filterable placeholder="选择使用车辆" @change="handleChange">
                <el-option
                  v-for="car in filteredCars"
                  :key="car.id"
                  :label="car.licensePlate"
                  :value="car.id">
                </el-option>
              </el-select>

            </el-form-item>
          </el-col>
        </el-row>


        <el-form-item label="前日迎检情况" prop="info">
          <el-input v-model="form.info" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="异常情况" prop="error">
          <el-input v-model="form.error" type="textarea" placeholder="请输入异常情况"/>
        </el-form-item>

        <el-divider content-position="center">污油罐信息</el-divider>
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="污油罐" prop="dirtyTankId">
              <el-select v-model="form.dirtyTankId" filterable placeholder="选择污油罐" @change="handleChange">
                <el-option
                  v-for="gas in filterdDirtyOilTanks"
                  :key="gas.id"
                  :label="gas.name"
                  :value="gas.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">


            <el-form-item label="污油罐高度(米)" prop="dirtyOilTankHeight">
              <div :style="{ border: '4px solid', borderColor: ( showPub && form.dirtyOilTankHeight >=  baojingHeight) ? 'red': ( showPub &&form.dirtyOilTankHeight >= yujingHeight) ?  'yellow': 'transparent',padding: '4px',borderRadius: '4px'}" >

                <!--                      :style="{ border: '4px solid',borderColor: (scope.row.tankType==3&&scope.row.tankHeight >= scope.row.baojingHeight) ? 'red': (scope.row.tankType==3&&scope.row.tankHeight >= scope.row.yujingHeight)? 'yellow': 'transparent',padding: '4px',borderRadius: '4px'}"-->

                <el-input-number :min='0' v-model="form.dirtyOilTankHeight" placeholder="请输入污油罐高度" :precision='3'/>
              </div>

            </el-form-item>


          </el-col>
          <el-col :span="8">
            <el-form-item label="污油罐库存" prop="dirtyOilTankWeight">

                <el-input-number :min='0' v-model="form.dirtyOilTankWeight" placeholder="请输入污油罐库存" :precision='3'/>

            </el-form-item>
          </el-col>
        </el-row>


        <!--        <el-form-item label="污油罐高度" prop="dirtyOilTankHeight" >-->
        <!--          <el-input-number :min = '0' v-model="form.dirtyOilTankHeight" placeholder="请输入污油罐高度"  :precision='4'>-->
        <!--          </el-input-number>-->
        <!--        </el-form-item>-->

        <!--        <el-form-item label="前日迎检情况" prop="info">-->
        <!--          <el-input v-model="form.info" placeholder="请输入前日迎检情况" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="异常情况" prop="error">-->
        <!--          <el-input v-model="form.error" placeholder="请输入异常情况" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="上报日期" prop="info">-->
        <!--        <el-date-picker clearable size="small"-->
        <!--                        v-model="form.reportDate"-->
        <!--                        type="date"-->
        <!--                        value-format="yyyy-MM-dd"-->
        <!--                        placeholder="选择上报日期">-->
        <!--        </el-date-picker>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="工作人员"  prop="workUsers">-->
        <!--          <el-select  v-model="form.workUsers" filterable multiple placeholder="选择工作人员" @change="handleChange">-->
        <!--            <el-option-->
        <!--              v-for="user in filteredUsers"-->
        <!--              :key="user.userId"-->
        <!--              :label="user.nickName + ' (' + user.userName + ')'"-->
        <!--              :value="user.userId">-->
        <!--            </el-option>-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->
        <el-form-item label="上报用户" prop="reportPerson">
          <el-select v-model="form.reportPerson" filterable placeholder="选择上报用户" @change="handleChange">
            <el-option
              v-for="user in filteredUsers"
              :key="user.userId"
              :label="user.nickName"
              :value="user.userId">
            </el-option>
          </el-select>

        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="validateAndSubmit">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="title" :visible.sync="openCar" width="500px" append-to-body>
      <el-form ref="carForm" :model="carForm" :rules="carRules" label-width="100px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="carForm.name" placeholder="请输入名称"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="carForm.remark" placeholder="请输入备注"/>
        </el-form-item>

        <el-form-item label="长度" prop="length">
          <el-input-number v-model="carForm.length" placeholder="请输入长度" :precision='4'>
          </el-input-number>
        </el-form-item>

        <el-form-item label="高度" prop="height">
          <el-input-number v-model="carForm.height" placeholder="请输入高度" :precision='4'>
          </el-input-number>
        </el-form-item>


        <el-form-item label="容量" prop="capacity">
          <el-input-number v-model="carForm.capacity" placeholder="请输入容量" :precision='4'>
          </el-input-number>
        </el-form-item>


        <el-form-item label="车牌号" prop="licensePlate">
          <LicensePlate v-model="carForm.licensePlate" @change="change"></LicensePlate>
        </el-form-item>

        <el-form-item label="物流车类型" prop="type">
          <el-select v-model="carForm.type" placeholder="请选择物流车类型">
            <el-option
              v-for="dict in typeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitCarForm">确 定</el-button>
        <el-button @click="cancelCar">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addStation,
  delStation,
  getStation,
  listStation,
  listStationNoAuthNoPage,
  updateStation
} from '@/api/station/station'
import {listUserNoPage} from '@/api/system/user'
import {addCar, listCarNoPage} from '@/api/report/car'
import {listTankNoPage} from '@/api/oiltank/tank'
import Treeselect from '@riophae/vue-treeselect'
import {treeselect} from '@/api/system/dept'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import {listSc} from "@/api/sc/sc";

export default {
  name: "Station",
  components: {Treeselect},
  data() {
    return {
      showPub : false,
      yujingHeight: '',
      baojingHeight: '',


      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      avgList: [],
      filterdOilTanks: [],
      filterdDirtyOilTanks: [],
      chineseNumbers: ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十'],
      // 物流车类型字典
      typeOptions: [],
      openCar: false,
      filteredCars: [],
      filteredUsers: [],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 航空加油站数据上报表格数据
      stationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 污油罐重量字典
      idOptions: [],
      // 名称字典
      nameOptions: [],
      // 创建时间字典
      createDateOptions: [],
      // 加油量字典
      fuelQuantityOptions: [],
      // 温度字典
      temperatureOptions: [],
      // 密度字典
      densityOptions: [],
      // 化验单编号字典
      sheetNoOptions: [],
      // 存油量字典
      oilStorageOptions: [],
      // 异常情况字典
      errorOptions: [],
      // 上报用户字典
      reportPersonOptions: [],
      // 当日使用车辆字典
      carIdOptions: [],
      // 工作人员字典
      workPersonOptions: [],
      // 污油罐高度字典
      dirtyOilTankHeightOptions: [],
      // 污油罐重量字典
      dirtyOilTankWeightOptions: [],
      // 查询参数
      queryParams: {
        dateQuery: [],
        pageNum: 1,
        pageSize: 10,
        name: null,
        createDate: null,
        fuelQuantity: null,
        temperature: null,
        density: null,
        sheetNo: null,
        oilStorage: null,
        error: null,
        reportPerson: null,
        carId: null,
        workPerson: null,
        dirtyOilTankHeight: null,
        dirtyOilTankWeight: null
      },
      currentDate: new Date(),
      workUsers: [],
      // 表单参数
      form: {
        cars: [],
        rate: [{}]
      },
      carForm: {},
      // 表单校验
      rules: {
        name: [
          {required: true, message: "数据日期不能为空", trigger: "blur"}
        ],
        dirtyTankId: [{required: true, message: "污油罐不能为空", trigger: "blur"},],
        fuelQuantity: [
          {required: true, message: "加油量不能为空", trigger: "blur"},
          {type: 'number', message: "加油量必须是数字", trigger: "blur"}
        ],
        oilCount: [
          {required: true, message: "加油架次不能为空", trigger: "blur"},
          {type: 'number', message: "加油架次必须是数字", trigger: "blur"}
        ],
        sheetNo: [
          {required: true, message: "化验单编号不能为空", trigger: "blur"}
        ],
        // oilStorage: [
        //   { required: true, message: "存油量不能为空", trigger: "blur" },
        //   { type: 'number', message: "存油量必须是数字", trigger: "blur" }
        // ],
        // error: [
        //   { required: false, message: "异常情况不能为空", trigger: "blur" }
        // ],
        reportPerson: [
          {required: true, message: "上报用户不能为空", trigger: "blur"}
        ],
        carId: [
          {required: true, message: "使用车辆不能为空", trigger: "blur"}
        ],
        // workPerson: [
        //   { required: true, message: "工作人员不能为空", trigger: "blur" }
        // ],
        workUsers: [
          {required: true, message: "工作人员不能为空", trigger: "blur"}
        ],
        dirtyOilTankHeight: [
          {required: true, message: "污油罐高度不能为空", trigger: "blur"},
          {type: 'number', message: "污油罐高度必须是数字", trigger: "blur"}
        ],
        dirtyOilTankWeight: [
          {required: true, message: "污油罐重量不能为空", trigger: "blur"},
          {type: 'number', message: "污油罐重量必须是数字", trigger: "blur"}
        ],
        // info: [
        //   { required: false, message: "前日迎检情况不能为空", trigger: "blur" }
        // ]
      },

      carRules: {
        name: [
          {required: true, message: "名称不能为空", trigger: "blur"}
        ],
        licensePlate: [
          {required: true, message: "车牌号不能为空", trigger: "blur"}
        ],
        type: [
          {required: true, message: "物流车类型不能为空", trigger: "change"}
        ],
      }
    };
  },
  created() {
    const routeDeptId = this.$route.query.deptId || null
    this.queryParams.deptId = routeDeptId
    this.getTreeselect()
    this.fetchUsers();
    this.fetchCars();
    this.getList();
    this.fetchOilTanks()
    this.fetchDirtyOilTanks()
    this.form.rate = [{temperature: null, density: null, divider: null}]
    this.getDicts("car_type").then(response => {
      this.typeOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.idOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.nameOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.createDateOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.fuelQuantityOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.temperatureOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.densityOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.sheetNoOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.oilStorageOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.errorOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.reportPersonOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.carIdOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.workPersonOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.dirtyOilTankHeightOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.dirtyOilTankWeightOptions = response.data;
    });
  },
  methods: {
    fetchOilTanks() {
      this.loading = true;
      // listTankNoPage().then(response => {
      //     this.filterdOilTanks = response.rows;
      //     this.loading = false;
      //   }

      listTankNoPage({auth: true}).then(response => {
          this.filterdOilTanks = response.rows
          this.filterdOilUsedTanks = response.rows.filter(tank => tank.typeId !== 3)

          // 初始化一个变量来存储累加结果
          let totalOilUsed = 0
          console.log("fetchOilTanks-----------")
// 遍历 this.filterdOilUsedTanks 数组
          this.filterdOilUsedTanks.forEach(tank => {
            // 获取 weight 和 min_cap 的值
            let weight = tank.weight || 0  // 假设字段存在，如果不存在则默认为 0
            let minCap = tank.minCap || 0 // 同理，默认值为 0

            // 将 weight 减去 min_cap 并累加到 totalOilUsed
            totalOilUsed += (weight - minCap)
          })

          listStationNoAuthNoPage().then(response => {
            this.stationList = response.rows
            // 获取当前日期
            const today = new Date()
            const sevenDaysAgo = new Date()
            sevenDaysAgo.setDate(today.getDate() - 7)
            this.avgList = this.stationList.filter(station => {
              const reportDate = new Date(station.reportDate)
              return reportDate >= sevenDaysAgo && reportDate <= today
            })

            let totalFuelQuantity = 0 // 初始化总加油量( 吨)
            console.log(this.avgList)
            this.avgList.forEach(station => {
              totalFuelQuantity += station.fuelQuantity || 0 // 避免 fuelQuantity 为 undefined 的情况
            })
            this.avgOil = this.avgList.length > 0
              ? totalFuelQuantity / this.avgList.length
              : 0 // 避免除以 0 的情况

            if (this.avgOil !== 0) {
              this.form.days = totalOilUsed / this.avgOil
            } else {
              this.form.days = 0
            }
          })

          if (!this.form.id) {
            this.filterdOilTanks.forEach(tank => {
              let obj = {}
              obj.extra1 = ''
              obj.extra2 = ''
              obj.extra3 = ''
              obj.extra4 = ''
              obj.deptId = ''
              obj.tankId = tank.id
              obj.tankWeight = tank.weight||0
              obj.tankHeight = tank.height||0
              obj.tankStatus = tank.status + ''
              obj.yujingHeight = tank.extra1 + ''
              obj.baojingHeight = tank.extra2 + ''
              obj.tankType = tank.typeId + ''
              obj.sheetNo = ''
              this.reportScDetailList.push(obj)
            })
          }
        }
      );
    },
    fetchDirtyOilTanks() {
      this.loading = true;
      let queryParams = {typeId: 3, status: 1}
      listTankNoPage(queryParams).then(response => {
          this.filterdDirtyOilTanks = response.rows;
          this.loading = false;
        }
      );
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data
      })
    },
    addDensityRow() {
      if (!Array.isArray(this.form.rate)) {
        this.$set(this.form, 'rate', []);
      }
      const oneSno = this.form.rate[0].sno;
      // 自动设置 level 值为当前行数 + 1
      const newLevel = this.form.rate.length + 1; // 计算新的 level
      this.form.rate.push({level: newLevel, temperature: 0, density: 0, sno: oneSno}); // 添加新行
    },
    removeDensityRow(index) {
      if (this.form.rate.length > 1) {
        this.form.rate.splice(index, 1);
      }
    },
    getDensityLabel(index) {
      // 中文数字数组
      const chineseNumbers = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十'];
      // 如果索引小于 10，直接返回对应的中文数字
      if (index < 10) {
        return chineseNumbers[index + 1] + '密';
      } else {
        // 处理十以上的数字：比如 "十一" 或 "十二"
        const tens = Math.floor((index + 1) / 10); // 取十位
        const units = (index + 1) % 10;            // 取个位
        let label = '十'; // 十位为 1 时

        if (tens > 1) {
          label = chineseNumbers[tens] + '十'; // 十位大于 1 的情况，如 "二十"
        }
        if (units > 0) {
          label += chineseNumbers[units]; // 添加个位
        }

        return label + '密';
      }
    },

    submitCarForm() {
      this.$refs["carForm"].validate(valid => {
        if (valid) {


          addCar(this.carForm).then(response => {
            this.msgSuccess("新增成功");
            this.openCar = false;
            this.fetchCars()
            this.carForm = {}
          });
        }
      });
    },
    openNewCar() {

      this.openCar = true;
      this.title = "添加物流车信息";
      this.carForm = {}
    },
    fetchUsers() {
      this.loading = true;
      listUserNoPage().then(response => {
          this.filteredUsers = response.rows || [];
          ;
          this.loading = false;
        }
      );
    },
    fetchCars() {
      this.loading = true;
      listCarNoPage().then(response => {
          this.filteredCars = response.rows || [];
          ;
          this.loading = false;
        }
      );
    },
    handleChange(value) {
      console.log("Selected user ID:", value)
      const oil = this.filterdDirtyOilTanks.find(oil => oil.id === value);
      this.yujingHeight = oil.extra1 + ''
      this.baojingHeight = oil.extra2 + ''
      this.showPub = true;
    },
    /** 查询航空加油站数据上报列表 */
    getList() {
      this.loading = true;
      listStation(this.queryParams).then(response => {
        this.stationList = response.rows || [];
        ;
        this.total = response.total;
        this.loading = false;


// 获取当前日期
        const today = new Date();

// 计算最近七天的日期
        const sevenDaysAgo = new Date();
        sevenDaysAgo.setDate(today.getDate() - 7);

// 筛选出 reportDate 在最近七天内的数据
        this.avgList = this.stationList.filter(station => {
          const reportDate = new Date(station.reportDate);
          return reportDate >= sevenDaysAgo && reportDate <= today;
        });

// 计算最近七天的总加油量和平均加油量
        let totalFuelQuantity = 0; // 初始化总加油量

// 遍历筛选后的集合，累加 fuelQuantity
        this.avgList.forEach(station => {
          totalFuelQuantity += station.fuelQuantity || 0; // 避免 fuelQuantity 为 undefined 的情况
        });
// 计算平均加油量
        this.form.avgOil = this.avgList.length > 0
          ? totalFuelQuantity / this.avgList.length
          : 0; // 避免除以 0 的情况
      });
    },
    workPersonFormat(row, column) {

      let workUsers = JSON.parse(row.extra2)
      if (!Array.isArray(workUsers)) {
        return '';
      }

      // 查找并格式化所有选中的用户
      const formattedUsers = workUsers.map(userId => {
        const user = this.filteredUsers.find(user => user.userId === userId);
        return user ? `${user.nickName}` : '';
      });
      console.log(formattedUsers)
      // 将所有格式化后的用户信息用逗号拼接
      let str= formattedUsers.filter(Boolean).join(', ');
      return str.split(',').map(name => name.trim()).join('<br>');
    },
    reportPersonFormat(row, column) {
      const user = this.filteredUsers.find(user => user.userId === row.reportPerson);

      return user ? user.nickName : '';
    },
    carFormat(row, column) {

      let cars = JSON.parse(row.carId)
      console.log(cars)
      if (!Array.isArray(cars)) {
        return '';
      }
      const formattedCars = cars.map(carId => {
        const car = this.filteredCars.find(car => car.id === carId);
        return car ? `${car.licensePlate}` : '';
      });

      let str = formattedCars.filter(Boolean).join(', ');
      return str.split(',').map(car => car.trim()).join('<br>');

    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    cancelCar() {
      this.openCar = false;
      this.title = ''
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        createDate: null,
        fuelQuantity: null,
        temperature: null,
        oilCount: null,
        density: null,
        sheetNo: null,
        oilStorage: null,
        error: null,
        reportPerson: null,
        carId: null,
        workPerson: null,
        dirtyOilTankHeight: null,
        dirtyOilTankWeight: null,
        rate: [{level: 1, temperature: 0, density: 0}]
      };

      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    change(val) {
      console.log(val.array)  //数组形式
      console.log(val.value)  //字符串形式
      console.log(val.pass)     //是否验证通过
    },
    /** 新增按钮操作 */
    handleAdd() {
      let av = this.form.avgOil
      this.reset();
      this.form.avgOil = av
      this.form.reportDate = new Date()
      this.open = true;
      this.title = "航空加油站数据上报";
      let currentUser = this.$store.state.user;
      this.form.reportPerson = currentUser.userId
      this.form.name = this.formattedDate()
    },
    formattedDate() {
      const year = this.currentDate.getFullYear();
      const month = String(this.currentDate.getMonth() + 1).padStart(2, '0');
      const day = String(this.currentDate.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getStation(id).then(response => {
        this.form = response.data;
        console.log(this.form)
        this.form.rate = JSON.parse(response.data.rateJson)
        this.open = true;
        this.title = "修改航空加油站上报数据";
        this.form.workUsers = JSON.parse(response.data.extra2)
        if (this.form.carId) {
          this.form.cars = JSON.parse(this.form.carId)
        }
      });
    },

    validateAndSubmit() {
      this.submitForm();
      // const reportDate = this.form.reportDate; // 获取表单中的 reportDate
      // const stationId = this.form.id;
      // console.log(stationId)
      // // 检查 reportDate 是否存在于 stationList 中
      // const exists = this.stationList.some(station => {
      //   if (stationId !== station.id) {
      //     return this.isSameDate(station.reportDate, reportDate);
      //   }
      // });
      //
      // if (exists) {
      //   this.$message.error("错误: 该日期已存在于加油记录中！");
      // } else {
      //   // 执行提交操作
      //   this.submitForm();
      // }
    },
    isSameDate(date1, date2) {
      // 转换日期为 Date 对象并比较
      const d1 = new Date(date1);
      const d2 = new Date(date2);

      return d1.getFullYear() === d2.getFullYear() &&
        d1.getMonth() === d2.getMonth() &&
        d1.getDate() === d2.getDate();
    },
    /** 提交按钮 */
    submitForm() {

      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateStation(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStation(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除航空加油站数据上报编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delStation(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('station/station/export', {
        ...this.queryParams
      }, `station_${new Date().getTime()}.xlsx`)

      // const queryParams = this.queryParams;
      // this.$confirm('是否确认导出所有航空加油站数据上报数据项?', "警告", {
      //     confirmButtonText: "确定",
      //     cancelButtonText: "取消",
      //     type: "warning"
      //   }).then(() => {
      //     this.exportLoading = true;
      //     return exportStation(queryParams);
      //   }).then(response => {
      //     this.download(response.msg);
      //     this.exportLoading = false;
      //   }).catch(() => {});
    }
  }
};
</script>
